﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChainOfResponsibilityPattern
{
    /// <summary>
    /// 抽象處理者
    /// </summary>
    public abstract class Handler
    {
       
        private Handler nextHandler;

        /// <summary>
        /// 每個處理者都必須對請求做出處理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response HandleMessage(Request request)
        {
            Response response = null;
            //判斷是否是自己的處理級別
            if (this.getHandlerLevel().Equals(request.getRequestLevel()))
            {
                response = this.echo(request);
            }
            else{ //不屬於自己的處理級別
                
                //判斷是否有下一個處理者
                if (this.nextHandler != null)
                {
                   response = this.nextHandler.HandleMessage(request);
                }
                else
                {
                    //沒有適當的處理者，業務自行處理
                }
            }
            return response;
        }

        /// <summary>
        /// 設置下一個處理者是誰
        /// </summary>
        /// <param name="_handler"></param>
        public void setNext(Handler _handler)
        {
            this.nextHandler = _handler;
        }
        /// <summary>
        /// 每個處理者都有一個處理級別  
        /// </summary>
        /// <returns></returns>
        public abstract Level getHandlerLevel();

        /// <summary>
        /// 每個處理者都必須實現處理任務
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public abstract Response echo(Request request);
        
    }

   
}
